Passed
Pull Request — master (#160)
by
unknown
01:51
created

util-text-encoding.ts ➔ encodingFromStringOrByte   A

Complexity

Conditions 3

Size

Total Lines 16
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 16
rs 9.75
c 0
b 0
f 0
cc 3
1
import iconv = require('iconv-lite')
2
import { isString } from "./util"
3
4
export function stringToEncodedBuffer(
5
    value: string,
6
    encodingByte: string | number
7
) {
8
    return iconv.encode(
9
        value,
10
        encodingFromStringOrByte(encodingByte)
11
    )
12
}
13
14
export function bufferToDecodedString(
15
    buffer: Buffer,
16
    encodingByte: string | number
17
) {
18
    return iconv.decode(
19
        buffer,
20
        encodingFromStringOrByte(encodingByte)
21
    ).replace(/\0/g, '')
22
}
23
24
function encodingFromStringOrByte(encoding: string | number) {
25
    const ENCODINGS = [
26
        'ISO-8859-1', 'UTF-16', 'UTF-16BE', 'UTF-8'
27
    ]
28
29
    if (isString(encoding) && ENCODINGS.includes(encoding)) {
30
        return encoding
31
    }
32
    if (
33
        typeof encoding === "number" &&
34
        encoding >= 0 && encoding < ENCODINGS.length
35
    ) {
36
        return ENCODINGS[encoding]
37
    }
38
    return ENCODINGS[0]
39
}
40
41